package com.zhenyi.youqu.admin.index;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.utils.PathUtils;
import com.utils.interceptor.TestInterceptor;
import com.youqu.common.model.YqCategory;
import com.youqu.common.model.YqGroup;
import com.youqu.common.model.YqItem;
import com.youqu.common.model.YqOrder;
import com.youqu.common.model.YqOrderInfo;
import com.youqu.common.model.YqProduct;
import com.youqu.common.model.YqShop;
import com.youqu.common.model.YqShopUser;
import com.youqu.common.model.YqUser;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;

public class OrderController extends YQAdminController {

	@Override
	public void list() {
		YqShopUser user = getShopUser();

		Date startTime = getStartTime();
		Date endTime = getEndTime();
		Kv kv = getSimpleKv("status", "outTradeNo", "transactionId", "trackNo", "isDeliverd", "hashId", "isUsed",
				"categoryId", "productType", "shopId");
		kv.set("startTime", startTime);
		kv.set("endTime", endTime);
		if (user.getRole().equals(YqShopUser.ROLE_SHOP)) {
			kv.set("shopId", user.getShopId());
		} else if (user.getRole().equals(YqShopUser.ROLE_ADMIN)) {
			kv.set("appId", user.getAppId());
		}
		SqlPara sqlPara = db.getSqlPara("YQAdminOrders", kv);
		SqlPara sp = db.getSqlPara("YQAdminOrdersSum", kv);
		Record result = db.findFirst(sp);
		if (result == null) {
			setData("sum", 0);
		} else if (result.getDouble("sum") != null) {
			Float sum = result.getDouble("sum").floatValue();
			setData("sum", sum / 100f);
		}

		int dl = getParaToInt("dl", 0);
		if (dl == 1) {
			Map<String, Object> sum = new LinkedHashMap<>();
			if (result.get("sum") != null) {
				sum.put("总价", "总价:" + (result.getDouble("sum").floatValue()) / 100);
			} else {
				sum.put("总价", "总价: 0");
			}
			// 查詢篩選后全部訂單
			List<Record> order = db.find(sqlPara);
			ArrayList<Map<String, Object>> rows = new ArrayList<>();
			for (Record record : order) {
				Map<String, Object> row2 = new LinkedHashMap<>();
				row2.put("日期", record.get("addTime"));
				row2.put("订单单号", record.get("out_trade_no"));
				int total_fee = (Integer.parseInt(record.get("total_fee")) / 100);
				row2.put("金额", total_fee);
				int paid = (int) record.get("paid") / 100;
				row2.put("支付金额", paid);
				row2.put("电话", record.get("record"));
				row2.put("内容", record.get("body"));
				row2.put("支付状态", record.get("trade_state"));
				if ((int) record.get("status") == 0) {
					row2.put("类型", "未支付");
				}
				if ((int) record.get("status") == 1) {
					row2.put("类型", "已支付");
				}
				if ((int) record.get("status") == -1) {
					row2.put("类型", "退款");
				}
				if ((int) record.get("status") == 2) {
					row2.put("类型", "关闭");
				}
				row2.put("商户", record.get("name"));
				row2.put("扫码支付",record.get("shopName"));
				rows.add(row2);
			}
			rows.add(sum);
			String path = PathUtils.getFile("data", "youqu", DateUtil.today() + "_订单.xlsx");
			System.out.println(path);
			// 通过工具类创建writer
			cn.hutool.poi.excel.ExcelWriter writer = ExcelUtil.getWriter(path);
			// 一次性写出内容
			writer.write(rows);
			// 关闭writer，释放内存
			writer.close();
			renderFile(new File(path));
		} else {
			// System.out.println(sqlPara);
			Page<Record> pages = db.paginate(getPage(), getPageSize(), sqlPara);
			setRainbow(pages);

			// setItems(JsonKit.toJson(pages.getList()));
			setData(pages.getList());
			SqlPara spShops = db.getSqlPara("YQShops", Kv.by("appId", user.getAppId()));
			List<Record> shops = db.find(spShops);
			setAttr("shops", JsonKit.toJson(shops));
			SqlPara sqlPara2 = db.getSqlPara("YQAdminCategories", Kv.by("appId", user.getAppId()));
			List<YqCategory> categories = YqCategory.dao.find(sqlPara2);
			setData("categories", categories);
			render("/yq/admin/order/list.html");
			// renderSuccess(pages.getList());
		}
	}

	/**
	 * 更新物流号
	 */
	public void updateTrackNo() {
		String trackNo = getPara("trackNo");
		if (StrKit.isBlank(trackNo)) {
			renderMsg("物流号为空");
			return;
		}
		Long orderId = getParaToLong("orderId");
		YqOrderInfo orderInfo = YqOrderInfo.dao.findById(orderId);
		orderInfo.setTrackNo(trackNo);
		orderInfo.update();
		renderSuccess();
	}

	@Override
	public void info() {
		Long orderId = getParaToLong("orderId");
		YqOrder order = YqOrder.dao.findById(orderId);
		setAttr("order", order);
		YqOrderInfo orderInfo = YqOrderInfo.dao.findById(orderId);
		if (orderInfo != null) {
			setData(orderInfo);
			Long productId = orderInfo.getProductId();
			if (productId != null) {
				setData("product", YqProduct.dao.findById(productId));
			}
			Long groupId = orderInfo.getGroupId();
			if (groupId != null) {
				setData("group", YqGroup.dao.findById(groupId));
			} else {
				// setAttr("group", "{}");
			}
			Long itemId = orderInfo.getItemId();
			if (itemId != null) {
				setData("item", YqItem.dao.findById(itemId));
			}
			Long userId = orderInfo.getUserId();
			setAttr("user", YqUser.dao.findById(userId));
		}

		Kv kv = Kv.create();
		kv.set("shopId", order.getShopId());
		SqlPara sp = db.getSqlPara("YQAdminShopUsers", kv);
		List<YqShopUser> shopUsers = YqShopUser.dao.find(sp);
		setData("shopUsers", shopUsers);

		render("/yq/admin/order/info.html");
	}

	public void query() {
		Long orderId = getParaToLong("orderId");
		YqOrder order = YqOrder.dao.findById(orderId);
		order.updateOrderStatus();
		order.updateOrderInfo();
		renderSuccess();
	}

	/**
	 * 订单退款
	 */
	public void refund() {
		Long orderId = getParaToLong("orderId");
		if (orderId == null) {
			renderError(404);
			return;
		}
		YqOrder order = YqOrder.dao.findById(orderId);
		if (order == null) {
			renderFailure("no order");
			return;
		}
		String fee = getPara("fee");
		String refundFee = StrKit.isBlank(fee) ? order.getPaid() + "" : fee;
		if ("0".equals(refundFee)) {
			refundFee = order.getTotalFee();
		}
		order.print();
		System.out.println("refundFee " + refundFee);
		Map<String, String> result = order.refund(refundFee);
		String result_code = result.get("result_code");
		if (!result_code.equals("SUCCESS")) {
			String message = result.get("err_code_des");
			renderMsg(message);
			return;
		}
		renderSuccess();
	}

	@Before(TestInterceptor.class)
	public void refund2() {
		Long orderId = getParaToLong("orderId");
		YqOrder order = YqOrder.dao.findById(orderId);
		String totalFee = order.getTotalFee();
		// Map<String, String> query = PaymentApi.queryByOutTradeNo(APP_ID,
		// PARTNER, PARTNER_KEY, order.getOutTradeNo());
		// if (PropKit.getBoolean("devMode", false)) {
		// System.out.println(JsonKit.toJson(query));
		// }
		// String trade_state = query.get("trade_state");
		// if (!("REFUND".equals(trade_state) || "SUCCESS".equals(trade_state)))
		// {
		// LogKit.info("订单支付状态非SUCCESS");
		// renderFailure("订单支付状态非SUCCESS");
		// return;
		// }
		String refundNo = orderId + "-refund-" + totalFee;
		String out_trade_no = order.getOutTradeNo();
		// String cash_fee = getCashFee();
		String total_fee = order.getPaid() + "";

		String refundFee = totalFee;
		if (PropKit.getBoolean("devMode", false)) {
			refundFee = "1";
		}
		order.refund(refundFee);
		// Map<?, ?> refund = payUtils.refundOrderNo(out_trade_no, total_fee,
		// refundFee, refundNo, REFUND_NOTIFY_URL);
		// System.out.println(JsonKit.toJson(refund));
		// boolean flag = PayUtils.isXMLSuccess(refund);
		renderSuccess();
	}

	/**
	 * 扫码支付/核销记录
	 */
	public void recordList() {
		Date startTime = getStartTime();
		Date endTime = getEndTime();
		Kv kv = getSimpleKv("shopId", "userName", "productName", "shopName", "shopUserName", "type");
		kv.set("startTime", startTime);
		kv.set("endTime", endTime);
		YqShopUser user = getShopUser();
		if (!user.getRole().equals(YqShopUser.ROLE_SUPER_ADMIN)) {
			kv.set("appId", user.getAppId());
		}
		if (user.getRole().equals(YqShopUser.ROLE_SHOP) || user.getRole().equals(YqShopUser.ROLE_VERIFIER)) {
			kv.set("shopId", user.getShopId());
		}
		SqlPara sqlPara = db.getSqlPara("YQAdminSaleRecord", kv);
		
		int dl = getParaToInt("dl", 0);
		if (dl == 1) {
			List<Record> list = db.find(sqlPara);
			ArrayList<Map<String, Object>> rows = new ArrayList<>();
			for (Record record : list) {
				Map<String, Object> row2 = new LinkedHashMap<>();
				row2.put("用户昵称", record.get("userName"));
				row2.put("产品名称", record.get("productName"));
				row2.put("商户名称", record.get("shopName"));
				row2.put("商户账户名", record.get("shopUserName"));
				row2.put("价格", record.get("price"));
				if ((int) record.get("type") == 0) {
					row2.put("类型", "扫码支付");
				} else if ((int) record.get("type") == 1) {
					row2.put("类型", "核销");
				}
				row2.put("日期", record.get("addTime"));
				rows.add(row2);
			}
			String path = PathUtils.getFile("data", "youqu", DateUtil.today() + "_核销记录.xlsx");
			// 通过工具类创建writer
			cn.hutool.poi.excel.ExcelWriter writer = ExcelUtil.getWriter(path);
			// 一次性写出内容
			writer.write(rows);
			// 关闭writer，释放内存
			writer.close();
			renderFile(new File(path));
			
		} else {
			Page<Record> pages = db.paginate(getPage(), getPageSize(), sqlPara);
			setRainbow(pages);
			setItems(pages.getList());
			SqlPara spShops = db.getSqlPara("YQShops", Kv.by("appId", user.getAppId()));
			List<Record> shops = db.find(spShops);
			setAttr("shops", JsonKit.toJson(shops));
			render("/yq/admin/order/recordList.html");
		}
	}

	/**
	 * 更新订单
	 */
	public void updateDeliver() {
		Long shopUserId = getParaToLong("shopUserId");
		if (shopUserId == null) {
			renderError(404);
			return;
		}
		YqShopUser shopUser = YqShopUser.dao.findById(shopUserId);
		if (shopUser == null) {
			renderError(404);
			return;
		}
		Long orderId = getParaToLong("orderId");
		if (orderId == null) {
			renderError(404);
			return;
		}
		YqOrder order = YqOrder.dao.findById(orderId);
		if (order == null) {
			renderError(404);
			return;
		}
		if (!order.getShopId().equals(shopUser.getShopId())) {
			renderError(404);
			return;
		}
		order.setShopUserId(shopUserId);
		order.update();
		renderSuccess();
	}

	public void recordInfo() {
	}
}
